package com.yb.mybatis.multi.datasource.config;

import com.yb.mybatis.multi.datasource.interceptor.MybatisMultiDatasourceInterceptor;
import com.yb.mybatis.multi.datasource.interfaces.ICurrentDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

/**
 * @author: yb
 * @date: 2021/12/30 0030 21:22
 */
@Configuration
@EnableConfigurationProperties(MybatisMultiDatasourceProperties.class)
@ConditionalOnProperty(prefix = "mybatis-multi-datasource",name = "enabled",havingValue = "true",matchIfMissing = true)
@ConditionalOnBean({SqlSessionFactory.class})
@AutoConfigureAfter({MybatisAutoConfiguration.class})
public class MybatisMultiDatasourceAutoConfig {

    @Autowired
    private MybatisMultiDatasourceProperties properties;

    @Autowired
    private List<SqlSessionFactory> sqlSessionFactoryList;

    @Autowired
    private ICurrentDataSource currentDataSource;

    @PostConstruct
    public void addPageInterceptor() {
        if(!properties.getEnabled()){
            return;
        }
        MybatisMultiDatasourceInterceptor interceptor = new MybatisMultiDatasourceInterceptor(currentDataSource);
        Properties properties = new Properties();
        properties.putAll(properties);
        interceptor.setProperties(properties);
        Iterator var3 = this.sqlSessionFactoryList.iterator();

        while(var3.hasNext()) {
            SqlSessionFactory sqlSessionFactory = (SqlSessionFactory)var3.next();
            sqlSessionFactory.getConfiguration().addInterceptor(interceptor);
        }
    }
}
